<script setup lang="ts">
import type { Dayjs } from 'dayjs';

import { ref } from 'vue';

import {
  ClockCircleOutlined,
  CrownOutlined,
  FileOutlined,
  HomeOutlined,
  LockOutlined,
  PlusOutlined,
  UnlockOutlined,
} from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import dayjs from 'dayjs';

interface TimeCapsule {
  id: string;
  title: string;
  description: string;
  createTime: string;
  unlockTime: string;
  status: 'locked' | 'pending' | 'unlocked';
  visibility: 'family' | 'public' | 'self';
  files: any[];
  creator: string;
}

interface Milestone {
  id: string;
  title: string;
  description: string;
  date: string;
  type: string;
  memberName: string;
  icon: any;
  color: string;
  hasSBT: boolean;
}

const activeTab = ref('all');
const showCreateModal = ref(false);
const viewModalVisible = ref(false);
const selectedCapsule = ref<null | TimeCapsule>(null);

const newCapsule = ref({
  title: '',
  description: '',
  unlockTime: null as Dayjs | null,
  visibility: 'family',
  files: [],
});

// Mock时间胶囊数据
const capsules = ref<TimeCapsule[]>([
  {
    id: 'capsule-1',
    title: '给未来子孙的信',
    description: '朱元璋亲笔家书，嘱托后世子孙勤政爱民',
    createTime: '1398-06-01T10:00:00Z',
    unlockTime: '2068-06-01T10:00:00Z',
    status: 'locked',
    visibility: 'family',
    files: [{ name: 'letter.pdf', size: 1_024_000 }],
    creator: '朱元璋',
  },
  {
    id: 'capsule-2',
    title: '永乐迁都决策记录',
    description: '迁都北京的战略考量与未来规划',
    createTime: '1421-01-01T10:00:00Z',
    unlockTime: '2121-01-01T10:00:00Z',
    status: 'locked',
    visibility: 'public',
    files: [{ name: 'decision.pdf', size: 2_048_000 }],
    creator: '朱棣',
  },
  {
    id: 'capsule-3',
    title: '家族创业历程',
    description: '记录朱氏家族从草根到皇室的奋斗历程',
    createTime: '1368-01-23T10:00:00Z',
    unlockTime: '2024-01-01T00:00:00Z',
    status: 'unlocked',
    visibility: 'family',
    files: [
      { name: 'history.pdf', size: 5_120_000 },
      { name: 'photos.zip', size: 10_240_000 },
    ],
    creator: '朱元璋',
  },
]);

// Mock里程碑数据
const milestones = ref<Milestone[]>([
  {
    id: 'm-1',
    title: '朱元璋登基称帝',
    description: '应天府登基，国号大明，年号洪武',
    date: '1368-01-23',
    type: 'political',
    memberName: '朱元璋',
    icon: CrownOutlined,
    color: 'gold',
    hasSBT: true,
  },
  {
    id: 'm-2',
    title: '朱棣迁都北京',
    description: '永乐十九年，正式迁都北京',
    date: '1421-01-01',
    type: 'political',
    memberName: '朱棣',
    icon: HomeOutlined,
    color: 'blue',
    hasSBT: true,
  },
  {
    id: 'm-3',
    title: '朱瞻基继位',
    description: '洪熙帝驾崩，宣德帝继位',
    date: '1425-05-29',
    type: 'succession',
    memberName: '朱瞻基',
    icon: CrownOutlined,
    color: 'gold',
    hasSBT: true,
  },
]);

function getCapsuleIcon(status: string) {
  const icons: Record<string, any> = {
    locked: LockOutlined,
    unlocked: UnlockOutlined,
    pending: ClockCircleOutlined,
  };
  return icons[status] || LockOutlined;
}

function getStatusColor(status: string) {
  const colors: Record<string, string> = {
    locked: 'blue',
    unlocked: 'green',
    pending: 'orange',
  };
  return colors[status] || 'default';
}

function getStatusText(status: string) {
  const texts: Record<string, string> = {
    locked: '已加密',
    unlocked: '已揭露',
    pending: '待确认',
  };
  return texts[status] || status;
}

function getVisibilityText(visibility: string) {
  const texts: Record<string, string> = {
    self: '仅本人',
    family: '家族可见',
    public: '公开',
  };
  return texts[visibility] || visibility;
}

function formatTime(time: string) {
  return dayjs(time).format('YYYY年MM月DD日 HH:mm');
}

function getTimeLeft(unlockTime: string) {
  const now = dayjs();
  const unlock = dayjs(unlockTime);
  return Math.max(0, unlock.diff(now, 'day'));
}

function viewCapsule(capsule: TimeCapsule) {
  selectedCapsule.value = capsule;
  viewModalVisible.value = true;
}

function disabledDate(current: Dayjs) {
  // 不能选择过去的日期
  return current && current < dayjs().endOf('day');
}

function beforeUpload(file: any) {
  const isLt10M = file.size / 1024 / 1024 < 10;
  if (!isLt10M) {
    message.error('文件大小不能超过10MB!');
  }
  return false; // 阻止自动上传
}

function handleCreateCapsule() {
  if (!newCapsule.value.title) {
    message.error('请输入标题');
    return;
  }
  if (!newCapsule.value.unlockTime) {
    message.error('请选择揭露时间');
    return;
  }

  message.loading('正在加密并上传到IPFS...', 3);
  setTimeout(() => {
    message.success('时间胶囊创建成功！已生成链上存证！');
    showCreateModal.value = false;
    newCapsule.value = {
      title: '',
      description: '',
      unlockTime: null,
      visibility: 'family',
      files: [],
    };
  }, 3000);
}

function downloadFile(file: any) {
  message.success(`正在解密并下载 ${file.name}...（Mock模式）`);
}
</script>

<template>
  <div class="timecapsule-page">
    <a-card>
      <template #title>
        <div class="page-header">
          <span>⏰ 时间胶囊 · 封存记忆</span>
          <a-button type="primary" @click="showCreateModal = true">
            <PlusOutlined /> 创建时间胶囊
          </a-button>
        </div>
      </template>

      <a-tabs v-model:active-key="activeTab">
        <a-tab-pane key="all" tab="全部胶囊">
          <a-row :gutter="16">
            <a-col
              v-for="capsule in capsules"
              :key="capsule.id"
              :span="8"
              style="margin-bottom: 16px"
            >
              <a-card hoverable @click="viewCapsule(capsule)">
                <div class="capsule-card">
                  <div class="capsule-icon">
                    <component :is="getCapsuleIcon(capsule.status)" />
                  </div>
                  <h4>{{ capsule.title }}</h4>
                  <p class="capsule-desc">{{ capsule.description }}</p>
                  <a-divider style="margin: 12px 0" />
                  <a-space direction="vertical" style="width: 100%">
                    <div class="capsule-meta">
                      <span
                        >📅 封存时间：{{ formatTime(capsule.createTime) }}</span
                      >
                    </div>
                    <div class="capsule-meta">
                      <span
                        >🔓 揭露时间：{{ formatTime(capsule.unlockTime) }}</span
                      >
                    </div>
                    <div v-if="capsule.status === 'locked'" class="countdown">
                      <a-statistic
                        :value="getTimeLeft(capsule.unlockTime)"
                        suffix="天后揭露"
                        :value-style="{ fontSize: '16px', color: '#1890ff' }"
                      />
                    </div>
                    <a-tag :color="getStatusColor(capsule.status)">
                      {{ getStatusText(capsule.status) }}
                    </a-tag>
                  </a-space>
                </div>
              </a-card>
            </a-col>
          </a-row>
        </a-tab-pane>

        <a-tab-pane key="milestones" tab="里程碑">
          <a-timeline>
            <a-timeline-item
              v-for="milestone in milestones"
              :key="milestone.id"
              :color="milestone.color"
            >
              <template #dot>
                <component :is="milestone.icon" style="font-size: 16px" />
              </template>
              <a-card size="small">
                <template #title>
                  <a-space>
                    <span>{{ milestone.title }}</span>
                    <a-tag v-if="milestone.hasSBT" color="green">
                      已铸造SBT
                    </a-tag>
                  </a-space>
                </template>
                <p>{{ milestone.description }}</p>
                <a-space>
                  <span>📅 {{ formatTime(milestone.date) }}</span>
                  <span>👤 {{ milestone.memberName }}</span>
                </a-space>
              </a-card>
            </a-timeline-item>
          </a-timeline>
        </a-tab-pane>
      </a-tabs>
    </a-card>

    <!-- 创建时间胶囊Modal -->
    <a-modal
      v-model:open="showCreateModal"
      title="创建时间胶囊"
      @ok="handleCreateCapsule"
      width="700px"
    >
      <a-form :model="newCapsule" layout="vertical">
        <a-form-item label="胶囊标题">
          <a-input
            v-model:value="newCapsule.title"
            placeholder="给时间胶囊起个名字"
          />
        </a-form-item>
        <a-form-item label="描述">
          <a-textarea
            v-model:value="newCapsule.description"
            :rows="3"
            placeholder="描述这个时间胶囊的内容..."
          />
        </a-form-item>
        <a-form-item label="揭露时间">
          <a-date-picker
            v-model:value="newCapsule.unlockTime"
            show-time
            style="width: 100%"
            :disabled-date="disabledDate"
            placeholder="选择未来的某个时间"
          />
        </a-form-item>
        <a-form-item label="可见性">
          <a-radio-group v-model:value="newCapsule.visibility">
            <a-radio value="self">仅本人</a-radio>
            <a-radio value="family">家族可见</a-radio>
            <a-radio value="public">公开</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="上传文件">
          <a-upload
            v-model:file-list="newCapsule.files"
            :before-upload="beforeUpload"
            list-type="picture-card"
          >
            <div>
              <PlusOutlined />
              <div style="margin-top: 8px">上传</div>
            </div>
          </a-upload>
          <a-alert
            message="文件将使用AES-256加密，并存储到IPFS，链上仅记录哈希"
            type="info"
            show-icon
            style="margin-top: 8px"
          />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 查看胶囊Modal -->
    <a-modal
      v-model:open="viewModalVisible"
      title="时间胶囊"
      width="700px"
      :footer="null"
    >
      <div v-if="selectedCapsule" class="capsule-detail">
        <h2>{{ selectedCapsule.title }}</h2>
        <p>{{ selectedCapsule.description }}</p>

        <a-descriptions :column="2" bordered style="margin: 16px 0">
          <a-descriptions-item label="创建时间">
            {{ formatTime(selectedCapsule.createTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="揭露时间">
            {{ formatTime(selectedCapsule.unlockTime) }}
          </a-descriptions-item>
          <a-descriptions-item label="状态">
            <a-tag :color="getStatusColor(selectedCapsule.status)">
              {{ getStatusText(selectedCapsule.status) }}
            </a-tag>
          </a-descriptions-item>
          <a-descriptions-item label="可见性">
            {{ getVisibilityText(selectedCapsule.visibility) }}
          </a-descriptions-item>
        </a-descriptions>

        <div
          v-if="selectedCapsule.status === 'unlocked'"
          class="capsule-content"
        >
          <h3>胶囊内容</h3>
          <a-space direction="vertical" style="width: 100%">
            <div
              v-for="file in selectedCapsule.files"
              :key="file.name"
              class="file-item"
            >
              <a-button type="link" @click="downloadFile(file)">
                <FileOutlined /> {{ file.name }}
              </a-button>
            </div>
          </a-space>
        </div>
        <a-alert
          v-else
          message="时间胶囊尚未到达揭露时间，内容已加密存储"
          type="warning"
          show-icon
        />
      </div>
    </a-modal>
  </div>
</template>

<style scoped lang="scss">
.timecapsule-page {
  .page-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
  }

  .capsule-card {
    text-align: center;

    .capsule-icon {
      margin-bottom: 16px;
      font-size: 48px;
      color: #1890ff;
    }

    h4 {
      margin: 0 0 8px;
      font-size: 16px;
    }

    .capsule-desc {
      min-height: 40px;
      margin-bottom: 12px;
      font-size: 13px;
      color: #666;
    }

    .capsule-meta {
      font-size: 12px;
      color: #999;
      text-align: left;
    }

    .countdown {
      padding: 12px;
      background: #e6f7ff;
      border-radius: 4px;
    }
  }

  .capsule-detail {
    h2 {
      margin-bottom: 12px;
    }

    h3 {
      margin: 24px 0 12px;
    }

    .file-item {
      padding: 8px;
      background: #fafafa;
      border-radius: 4px;
    }
  }
}
</style>
